import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'HomeFilled', affix: true }
      }
    ]
  },
  {
    path: '/user',
    component: () => import('@/layout/index.vue'),
    redirect: '/user/list',
    meta: { title: '用户管理', icon: 'User' },
    children: [
      {
        path: 'list',
        name: 'UserList',
        component: () => import('@/views/user/index.vue'),
        meta: { title: '用户列表', icon: 'List' }
      }
    ]
  },
  {
    path: '/chat',
    component: () => import('@/layout/index.vue'),
    redirect: '/chat/history',
    meta: { title: '聊天历史', icon: 'ChatDotRound' },
    children: [
      {
        path: 'history',
        name: 'ChatHistory',
        component: () => import('@/views/chat/history/index.vue'),
        meta: { title: '聊天历史', icon: 'Document' }
      }
    ]
  },
  {
    path: '/member',
    component: () => import('@/layout/index.vue'),
    redirect: '/member/level',
    meta: { title: '会员管理', icon: 'Crown' },
    children: [
      {
        path: 'level',
        name: 'MemberLevel',
        component: () => import('@/views/member/level/index.vue'),
        meta: { title: '会员等级', icon: 'Medal' }
      },
      {
        path: 'order',
        name: 'MemberOrder',
        component: () => import('@/views/member/order/index.vue'),
        meta: { title: '会员订单', icon: 'Tickets' }
      }
    ]
  },
  {
    path: '/quota',
    component: () => import('@/layout/index.vue'),
    redirect: '/quota/package',
    meta: { title: '配额包管理', icon: 'Wallet' },
    children: [
      {
        path: 'package',
        name: 'QuotaPackage',
        component: () => import('@/views/quota/package/index.vue'),
        meta: { title: '配额包', icon: 'Box' }
      },
      {
        path: 'order',
        name: 'QuotaOrder',
        component: () => import('@/views/quota/order/index.vue'),
        meta: { title: '配额订单', icon: 'List' }
      }
    ]
  },
  {
    path: '/sensitive',
    component: () => import('@/layout/index.vue'),
    redirect: '/sensitive/word',
    meta: { title: '敏感词管理', icon: 'Warning' },
    children: [
      {
        path: 'word',
        name: 'SensitiveWord',
        component: () => import('@/views/sensitive/word/index.vue'),
        meta: { title: '敏感词', icon: 'Lock' }
      }
    ]
  },
  {
    path: '/share',
    component: () => import('@/layout/index.vue'),
    redirect: '/share/list',
    meta: { title: '分享管理', icon: 'Share' },
    children: [
      {
        path: 'list',
        name: 'ShareList',
        component: () => import('@/views/share/list/index.vue'),
        meta: { title: '分享列表', icon: 'List' }
      }
    ]
  },
  {
    path: '/prompt',
    component: () => import('@/layout/index.vue'),
    redirect: '/prompt/template',
    meta: { title: '提示词模板', icon: 'CollectionTag' },
    children: [
      {
        path: 'template',
        name: 'PromptTemplate',
        component: () => import('@/views/prompt/template/index.vue'),
        meta: { title: '模板管理', icon: 'List' }
      }
    ]
  },
  {
    path: '/system',
    component: () => import('@/layout/index.vue'),
    redirect: '/system/monitor',
    meta: { title: '系统监控', icon: 'Monitor' },
    children: [
      {
        path: 'monitor',
        name: 'SystemMonitor',
        component: () => import('@/views/system/monitor/index.vue'),
        meta: { title: '系统监控', icon: 'DataLine' }
      }
    ]
  },
  {
    path: '/profile',
    component: () => import('@/layout/index.vue'),
    meta: { title: '个人中心', icon: 'User', hidden: true },
    children: [
      {
        path: 'index',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心', icon: 'User', activeMenu: '/profile' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/layout/index.vue'),
    redirect: '/404',
    children: [
      {
        path: '404',
        name: '404',
        component: () => import('@/views/error/404.vue'),
        meta: { title: '404', hidden: true }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 嘿鸽AI管理系统` : '嘿鸽AI管理系统'
  
  // 白名单，不需要登录就可以访问
  const whiteList = ['/login', '/404']
  
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  
  // 获取token
  const hasToken = userStore.token
  
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      // 判断是否已经获取用户信息
      const hasUserInfo = userStore.userInfo.id
      
      if (hasUserInfo) {
        next()
      } else {
        try {
          // 获取用户信息
          await userStore.getUserInfoAction()
          next()
        } catch (error) {
          // 获取用户信息失败，可能是token过期，跳转到登录页
          await userStore.logoutAction()
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    // 没有token，跳转到登录页
    next(`/login?redirect=${to.path}`)
  }
})

// 路由后置守卫
router.afterEach(() => {
  // 关闭页面加载进度条
  // NProgress.done()
})

export default router